import axios from 'axios'
import qs from 'qs'
import {
	ElMessage
} from 'element-plus';

const http = {}

let base_url;
if(process.env.NODE_ENV == 'development') {
	base_url = 'http://zu.zsxlwangge.com'; // 开发环境/测试环境
} else if(process.env.NODE_ENV == 'production') {
	base_url = 'http://36.137.224.120:9501';
} else if(process.env.NODE_ENV == 'test') {
	base_url = 'http://zu.zsxlwangge.com';
}

const Axios = axios.create({
	timeout: 200000,
	baseURL: base_url,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
	},
	validateStatus(status) {
		return status >= 200 && status < 300;
	}
});


// 请求拦截
Axios.interceptors.request.use(config => {
	let TOKEN = localStorage.getItem('token');
	config.headers.common['Authorization'] = 'Bearer ' + TOKEN;
	return config;
}, err => {
	return Promise.reject(err);
})

// 响应拦截
Axios.interceptors.response.use(res => {
	res.headers.authorization != undefined ? (localStorage.setItem('token', res.headers.authorization),window.location.reload()) : res;
	if (res.config.url === "/login") {
		return res;
	} else {
		return res;
	}
}, err => {
	console.log(err.response)
	switch (err.response.status) {
		case 401:
			ElMessage({
				showClose: true,
				message: err.response.data.msg ? err.response.data.msg : err.response.data.message,
				type: 'error'
			})
			this.$router.replace('/login');
			localStorage.removeItem('token');
			window.location.reload();
			break;
		case 422:
			ElMessage({
				showClose: true,
				message: err.response.data.msg ? err.response.data.msg : err.response.data.message,
				type: 'error'
			})
			return;
		case 403:
			ElMessage({
				showClose: true,
				message: err.response.data.msg ? err.response.data.msg : err.response.data.message,
				type: 'error'
			})
			break;
		case 404:
			ElMessage({
				showClose: true,
				message: err.response.data.msg ? err.response.data.msg : err.response.data.message,
				type: 'error'
			})
			break;
		case 500:
			ElMessage({
				showClose: true,
				message: err.response.data.msg ? err.response.data.msg : err.response.data.message,
				type: 'error'
			})
			break;
	}
	return Promise.reject(err)
})

http.get = function(url, data = {}) {
	return new Promise((resolve, reject) => {
		Axios.get(url, {
			params: data
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err);
		})
	})
}

http.del = function(url, data = {}) {
	return new Promise((resolve, reject) => {
		Axios.delete(url, {
			params: data
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err);
		})
	})
}

http.post = function(url, data) {
	return new Promise((resolve, reject) => {
		Axios.post(url, qs.stringify(data)).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err);
		})
	})
}


export default http
